﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;

namespace CuaHangLego.DataAccess
{
    public abstract class DABase
    {
        static string server = "TRUONGTOAN-PC\\SQLEXPRESS";
        static string db = "CUAHANGLEGO";
        static int connectionTimeout = 30;
        static string sqlConnectString = "User Id=truongtoan;Password=flamingo1;Server=" + server + ";Trusted_Connection=yes;Database=" + db + "; Connection Timeout=" + connectionTimeout;
        //SqlConnection Connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnectionStringWithAccount"].ConnectionString);
        SqlConnection Connection = new SqlConnection(sqlConnectString);

        protected bool OpenDB()
        {
            try
            {
                Connection.Open();
            }
            catch
            {
                return false;
            }
            return true;
        }

        protected void CloseDB()
        {
            Connection.Close();
        }

        protected int ExecuteQuery(SqlCommand myCommand)
        {
            int rs = 0;
            try
            {
                myCommand.Connection = Connection;
                myCommand.CommandType = System.Data.CommandType.Text;
                rs = myCommand.ExecuteNonQuery();
            }
            catch (SqlException e)
            {
                Console.WriteLine("Database error: " + e.Message);
            }
            return rs;
        }

        protected SqlDataReader ExecuteQueryReader(SqlCommand myCommand)
        {
            SqlDataReader rs = null;
            try
            {
                myCommand.Connection = Connection;
                myCommand.CommandType = System.Data.CommandType.Text;
                rs = myCommand.ExecuteReader();
            }
            catch (SqlException e)
            {
                Console.WriteLine("Database error: " + e.Message);
            }

            return rs;
        }

        protected object ExecuteQuerySingleValue(SqlCommand myCommand)
        {
            object rs = null;
            try
            {
                myCommand.Connection = Connection;
                myCommand.CommandType = System.Data.CommandType.Text;
                rs = myCommand.ExecuteScalar();
            }
            catch (SqlException e)
            {
                Console.WriteLine("Database error: " + e.Message);
            }

            return rs;
        }
    }
}
